package com.oscar.ehome.view.teamview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.teamBean.TeamListBean;
import com.oscar.ehome.bean.teamBean.UserAppInfoBean;
import com.oscar.ehome.bean.teamBean.UserRoleStaticBean;
import com.oscar.ehome.bean.teamBean.UserStartStaticBean;
import com.oscar.ehome.presenter.TeamPresenter;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.teamview.adapter.StarssGvAdapter;
import com.oscar.ehome.view.teamview.view.TeamListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PieChartView;

import static com.oscar.ehome.R.id.count;

public class TeamCountViewActivity extends BasesActivity<TeamListView, TeamPresenter> implements TeamListView, AdapterView.OnItemClickListener {

    /**
     * 筛选统计图
     */
    @BindView(R.id.liear_spinner)
    LinearLayout liearSpinner;
    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 列表
     */
    @BindView(R.id.gv_list)
    GridView gvList;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 团队人数
     */
    @BindView(R.id.member_tem)
    TextView memberTem;
    /**
     * 人数
     */
    @BindView(R.id.member_popple)
    TextView memberPopple;
    /**
     * 柱状图
     */
    ColumnChartView barChart;
    /**
     * 姓名
     */
    @BindView(R.id.member_team_name)
    TextView memberTeamName;
    /**
     * 饼状图
     */
    PieChartView pieChart;
    /**
     * 星级统计  or  职级统计
     */
    @BindView(R.id.liear_text)
    TextView liearText;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.qiehuantu)
    ImageView qiehuantu;

    TeamPresenter teamPresenter;
    private StarssGvAdapter adapter;
    List<UserRoleStaticBean.ListBean> list;
    List<UserStartStaticBean.StartsListBean> startslist;
    String name = "";//名字
    int bar = 1;//柱状图   or   扇形图
    String ids = "";//id
    boolean isFirst = true;//是不是第一次进来

    List<Integer> listpre_color = new ArrayList<>();//饼状图颜色
    List<Integer> listchatr_color = new ArrayList<>();//柱状图颜色
    private ColumnChartData mColumnChartData;    //柱状图数据
    //数据
    private PieChartData pieChardata;
    UserRoleStaticBean bean;
    List<Integer> list_color = new ArrayList<>();//全部颜色
    List<Integer> list_allcolor = new ArrayList<>();//全部颜色


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_bar_view);
        ButterKnife.bind(this);
        setbaseColor();
        iniView();
        SetColor();
        initData();
       //initPreData();
    }

    @Override
    protected TeamPresenter createPresenter() {
        teamPresenter = new TeamPresenter(this);
        return teamPresenter;
    }

    /**
     * 设置颜色
     */
    public void setbaseColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(TeamCountViewActivity.this).getSystemConfig().getColor()));
        liearText.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(qiehuantu, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    /**
     * 初始化view
     */
    private void iniView() {
        barChart = (ColumnChartView) findViewById(R.id.barChart);
        pieChart = (PieChartView) findViewById(R.id.pie_chart);

        gvList.setOnItemClickListener(this);

        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleTopbar.setText(R.string.team_count);

        name = getIntent().getStringExtra("member_name");
        if (name != null) {
            memberTeamName.setText(name);
            memberTem.setText(name + "团队人数：");
        } else {
            memberTeamName.setText("");
            memberTem.setText("团队人数：");
        }
        ids = getIntent().getStringExtra("id");

        barChart.setVisibility(View.VISIBLE);
        pieChart.setVisibility(View.GONE);

    }

    /**
     * 颜色赋值
     */
    public void SetColor() {
        list_color.add(R.color.chart_red);
        list_allcolor.add(Color.rgb(254, 0, 0));
        list_color.add(R.color.chart_orgn);
        list_allcolor.add(Color.rgb(233, 123, 34));
        list_color.add(R.color.chatr_yellow);
        list_allcolor.add(Color.rgb(253, 206, 16));
        list_color.add(R.color.chart_green);
        list_allcolor.add(Color.rgb(27, 214, 159));
        list_color.add(R.color.chart_parint);
        list_allcolor.add(Color.rgb(252, 128, 221));
        list_color.add(R.color.chart_bule);
        list_allcolor.add(Color.rgb(97, 192, 222));
        list_color.add(R.color.chart_bggreen);
        list_allcolor.add(Color.rgb(43, 113, 125));
        list_color.add(R.color.chart_zise);
        list_allcolor.add(Color.rgb(150, 75, 185));
        list_color.add(R.color.chart_gren);
        list_allcolor.add(Color.rgb(155, 202, 98));
        list_color.add(R.color.chart_bgbule);
        list_allcolor.add(Color.rgb(65, 84, 185));
    }

    /**
     * 柱状图加载数据
     */
    public void initData() {
        teamPresenter.LoadUserRoleStatisticsAppList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(),
                ids);
        showLoading();
    }

    /**
     * 扇形图加载数据
     */
    public void initPreData() {
        teamPresenter.LoadUserStartStatisticsAppList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(),
                ids);
        showLoading();
    }

    /**
     * 设置饼状图数据
     */
    public void initPieData(List<UserStartStaticBean.StartsListBean> list) {
        List<SliceValue> values = new ArrayList<SliceValue>();
        int count = 0;


        if (list.size() > 0) {

            for (int i = 0; i < list.size(); i++) {

                UserStartStaticBean.StartsListBean jobListBean = list.get(i);
                if (jobListBean != null) {

                    int leves = jobListBean.getStarLevel();
                    int number = jobListBean.getRoleMobileUserNum();

                    SliceValue sliceValue = new SliceValue((float) number, list_allcolor.get(i));
                    values.add(sliceValue);

//                    if (leves == 0) {
//                        xValues.add("零星");
//                    } else if (leves == 1) {
//                        xValues.add("一星");
//                    } else if (leves == 2) {
//                        xValues.add("二星");
//                    } else if (leves == 3) {
//                        xValues.add("三星");
//                    }
                    count += number;

                }
            }
        }
        memberPopple.setText(count + "人");
        if(bean.getCount()<=0){
            ToastUtil.show(TeamCountViewActivity.this, "暂无星级规则");
        }else{
            if (count > 0) {
            liearText.setText("职级统计");
            bar = 2;
            barChart.setVisibility(View.GONE);
            pieChart.setVisibility(View.VISIBLE);

            if (!isFirst) {
                adapter = new StarssGvAdapter(TeamCountViewActivity.this, startslist, 1, listpre_color);
                gvList.setAdapter(adapter);
            }

            pieChardata = new PieChartData();
            pieChardata.setHasLabels(true);//显示表情
            pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
            pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
            pieChardata.setHasCenterCircle(false);//是否是环形显示
            pieChardata.setSlicesSpacing(3);
            pieChardata.setValues(values);//填充数据
            pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
            pieChardata.setCenterCircleScale(0.5f);//设置环形的大小级别
            pieChart.setPieChartData(pieChardata);
            pieChart.setValueSelectionEnabled(true);//选择饼图某一块变大
            pieChart.setAlpha(0.9f);//设置透明度
            pieChart.setCircleFillRatio(1f);//设置饼图大小
            pieChart.setPieChartData(pieChardata);
        } else {
                ToastUtil.show(TeamCountViewActivity.this, "团队暂无星级人员");
        }
        }
    }

    /**
     * 设置柱状图数据
     */
    public void initBarchatData(List<UserRoleStaticBean.ListBean> list) {
        /*========== 柱状图数据填充 ==========*/
        List<Column> columnList = new ArrayList<>(); //柱子列表
        List<SubcolumnValue> subcolumnValueList;     //子柱列表（即一个柱子，因为一个柱子可分为多个子柱）
        List<AxisValue> axisValues = new ArrayList<>();
        int count = 0;

        for (int i = 0; i < list.size(); ++i) {
            subcolumnValueList = new ArrayList<>();
            UserRoleStaticBean.ListBean jobListBean = list.get(i);

            if (jobListBean.getRoleMobile() != null) {
                int number = jobListBean.getRoleMobileUserNum();
                subcolumnValueList.add(new SubcolumnValue((float) number, list_allcolor.get(i)));
                Column column = new Column(subcolumnValueList);
                column.setHasLabels(true);                    //设置列标签
                columnList.add(column);

                //设置坐标值
                axisValues.add(new AxisValue(i).setLabel(jobListBean.getRoleMobile().getRoleName()));
                count += number;
            }
        }
        memberPopple.setText(count + "人");
        mColumnChartData = new ColumnChartData(columnList);               //设置数据

        /*===== 坐标轴相关设置 =====*/
        Axis axisX = new Axis(axisValues); //将自定义x轴显示值传入构造函数
        Axis axisY = new Axis().setHasLines(true); //setHasLines是设置线条
        axisX.setName("");    //设置横轴名称
        axisY.setName("");    //设置竖轴名称
        mColumnChartData.setAxisXBottom(axisX); //设置横轴
        mColumnChartData.setAxisYLeft(axisY);   //设置竖轴

        //以上所有设置的数据、坐标配置都已存放到mColumnChartData中，接下来给mColumnChartView设置这些配置
        barChart.setColumnChartData(mColumnChartData);
        /*===== 设置竖轴最大值 =====*/
        //法一：
        Viewport v = barChart.getMaximumViewport();
        v.top = 50;
        barChart.setCurrentViewport(v);
        /*法二：
        Viewport v = mColumnChartView.getCurrentViewport();
        v.top = 100;
        mColumnChartView.setMaximumViewport(v);
        mColumnChartView.setCurrentViewport(v);*/
    }

    @OnClick({R.id.title_layout_left, R.id.liear_spinner})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left:
                finish();
                break;
            case R.id.liear_spinner://筛选
                isFirst = false;
                if (bar == 1) {//现在是柱状图，切换为扇形图
                    initPreData();
                } else if (bar == 2) {
                    bar = 1;
                    liearText.setText("星级统计");
                    barChart.setVisibility(View.VISIBLE);
                    pieChart.setVisibility(View.GONE);
                    initData();
                }
                break;
        }
    }

    @Override
    public void LoadUserTeamAppList(TeamListBean TeamListBean) {

    }

    @Override
    public void getRoalList(TeamListBean TeamListBean) {

    }

    @Override
    public void getStartLeves(TeamListBean TeamListBean) {

    }

    /**
     * 职级统计图数据
     *
     * @param userRoleStaticBean
     */
    @Override
    public void LoadUserRoleStatisticsAppList(UserRoleStaticBean userRoleStaticBean) {
        dismissLoading();
        list = new ArrayList<>();
        listchatr_color = new ArrayList<>();
        list = userRoleStaticBean.getList();
        bean=userRoleStaticBean;



        Log.e("count", "initBarchatData: "+bean.getCount() );
        if (list.size() > 0) {
            adapter = new StarssGvAdapter(TeamCountViewActivity.this, list, listchatr_color);
            gvList.setAdapter(adapter);
            initBarchatData(list);
            for (int i = 0; i < list.size(); i++) {
                listchatr_color.add(list_color.get(i));
            }
        }

    }

    /**
     * 星级统计数据
     *
     * @param userStartStaticBean
     */
    @Override
    public void LoadUserStartStatisticsAppList(UserStartStaticBean userStartStaticBean) {
        dismissLoading();
        startslist = new ArrayList<>();
        listpre_color = new ArrayList<>();
        startslist = userStartStaticBean.getList();

        initPieData(startslist);
        for (int i = 0; i < startslist.size(); i++) {
            listpre_color.add(list_color.get(i));
        }
    }

    @Override
    public void LoadUserAppInfo(UserAppInfoBean userAppInfoBean) {

    }

    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(TeamCountViewActivity.this, getString(R.string.erry));

    }

    @Override
    public void erry(String result) {
        dismissLoading();
        Toast.makeText(TeamCountViewActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (bar == 1) {//现在是柱状图
            if (list.get(position).getRoleMobileUserNum() != 0) {
                Intent intent = new Intent(TeamCountViewActivity.this, TeamListActivity.class);
                intent.putExtra("id", ids);//个人ID
                intent.putExtra("ids", list.get(position).getRoleMobile().getId());//职级ID
                intent.putExtra("name", list.get(position).getRoleMobile().getRoleName());
                intent.putExtra("chaungtuan", 1);
                intent.putExtra("chaun", 1);
                startActivity(intent);
//                finish();
            } else {
                ToastUtil.show(TeamCountViewActivity.this, R.string.tjnodatamesage);
            }
        } else if (bar == 2) {//现在是扇形图
            if (startslist.get(position).getRoleMobileUserNum() != 0) {
                UserStartStaticBean.StartsListBean bean = startslist.get(position);
                int leves = bean.getStarLevel();
                Intent intent = new Intent(TeamCountViewActivity.this, TeamListActivity.class);
                intent.putExtra("id", ids);//个人ID
                intent.putExtra("ids", leves + "");//星级ID
                intent.putExtra("name", leves + "");
                intent.putExtra("chaungtuan", 1);
                intent.putExtra("chaun", 3);
                startActivity(intent);
//                finish();
            } else {
                ToastUtil.show(TeamCountViewActivity.this, R.string.start_nodatamesage);
            }
        }
    }
}
